package bit_poi.utils;

import cn.hutool.core.lang.Console;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import java.io.IOException;
import java.io.InputStream;

/**
 * @author yuisama
 * @date 2023/01/03 17:17
 * MyBatis数据源和连接生成工具类
 **/
public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        InputStream in;
        try {
            // 获取mybatis配置文件
            String resouces = "mybatis-config.xml";
            in = Resources.getResourceAsStream(resouces);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
            Console.log("mybatis数据源创建成功");
        } catch (IOException e) {
            Console.error("创建mybatis数据源失败");
            e.printStackTrace();
        }
    }

    // 获取连接
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}
